import { View } from "@tarojs/components";
import {
  AbstractImage,
  C13BottomDock,
  C40TermsAndConditions,
  CheckBox,
  Icon,
  Paragraph,
  PriceView,
  UserSubPageBase,
} from "@/components";
import { CartItemShape } from "@/data/user/userTypes";
import { colors } from "@/data/shared/colors";
import { navigateTo } from "@/utils/navigation";
import { useEffect, useState } from "react";
import style from "./index.module.scss";
import { useUserInfo, changeUserCart } from "@/store/userDataContext";

type CartProps = {
  cartItems: CartItemShape[];
  removeCallback?: Function;
  handleSubmit: Function;
};

const quantityAvailable = (cartItem: CartItemShape) =>
  cartItem.availability >= cartItem.quantity &&
  cartItem.availability !== 0 &&
  cartItem.attrStatus;

const C33ShoppingCart = ({
  cartItems,
  removeCallback,
  handleSubmit,
}: CartProps) => {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData } = userInfoState;
  const [checkedItems, setCheckedItems] = useState<number[]>([]);
  const [agreedToC, setAgreedToC] = useState(false);
  const [arrayLength, setArrayLength] = useState(0);

  // Initialize state once data comes in
  useEffect(() => {
    setArrayLength(cartItems.length);
    setCheckedItems(
      cartItems.filter(quantityAvailable).map((cartItem) => cartItem.id)
    );
  }, [cartItems]);

  useEffect(() => {
    dispatchUserDataAction({
      type: "CART_SELECT",
      data: checkedItems,
    });
  }, [checkedItems]);

  const removeCartItem = async (i, id) => {
    if (removeCallback) {
      (await removeCallback([id], i)) === false ? true : false;
    }
  };

  const changeCartItem = async (i, id, quantity) => {
    if (quantity > 0) {
      await changeUserCart(dispatchUserDataAction, {
        query: {
          id: id,
          quantity: quantity,
        },
      });
    } else {
      removeCartItem(i, id);
    }
  };

  return (
    <UserSubPageBase
      title="购物车"
      subTitleDark={`您的购物车里有${arrayLength}个商品`}
    >
      {/* Cart item listing */}
      <View className={`title-s ${style["cart-items-listing"]}`}>
        {cartItems.map((cartItem, index) => {
          const available = quantityAvailable(cartItem);
          return (
            <View
              key={`${cartItem.itemType}-${cartItem.id}`}
              className={style["cart-item-container"]}
              style={!available ? { filter: "grayscale(1)", opacity: 0.4 } : {}}
            >
              <CheckBox
                onChangeCb={(e) => {
                  const checked = !!e.detail.value.length;
                  setCheckedItems((prevCheckedItemsList) => {
                    if (checked) {
                      return [...prevCheckedItemsList, cartItem.id];
                    } else {
                      return prevCheckedItemsList.filter(
                        (val) => val !== cartItem.id
                      );
                    }
                  });
                }}
                intiallyChecked
                hideCheckbox={!available}
                checked={checkedItems.includes(cartItem.id)}
              />
              {/* Left side */}
              <AbstractImage
                type="about-sub-page-list"
                src={cartItem.imagePath}
              />
              {/* Right side */}
              <View className={style["content-container"]}>
                <View className={style["top-content-container"]}>
                  <View
                    className={`title-s ${style["cart-items-title"]}`}
                    style={{ color: cartItem.tagColor }}
                  >
                    {cartItem.categoryName || cartItem.tag}
                  </View>

                  {removeCallback && (
                    <Icon
                      type="Delete"
                      className={style["delete-icon"]}
                      onClick={() => removeCartItem(index, cartItem.id)}
                    />
                  )}

                  <View className={style["name-container"]}>
                    <View className={style["name"]}>{cartItem.name}</View>
                    {cartItem.tag !== "default" && (
                      <View className={style["tag"]}>{cartItem.tag}</View>
                    )}
                  </View>

                  {/* Quantity selector - During testing need to see if clickable area large enough */}
                  <View className={style["quantity-selector"]}>
                    <View
                      className={`${style["quantity-selector-adjustment"]} ${style["left"]}`}
                      onClick={() => {
                        changeCartItem(
                          index,
                          cartItem.id,
                          cartItem.quantity - 1
                        );
                      }}
                    >
                      <Icon type="Minus" className={style["minus-icon"]} />
                    </View>
                    <View className={style["quantity-selector-number"]}>
                      {cartItem.quantity}
                    </View>
                    <View
                      className={`${style["quantity-selector-adjustment"]} ${style["right"]}`}
                      onClick={() => {
                        changeCartItem(
                          index,
                          cartItem.id,
                          cartItem.quantity + 1
                        );
                      }}
                    >
                      <Icon type="Plus" className={style["plus-icon"]} />
                    </View>
                  </View>
                </View>

                {/* Price */}
                <PriceView
                  className={style["price"]}
                  price={cartItem.unitPrice}
                  type="small"
                />

                {/* Goto detail page */}
                <Icon
                  type="Arrow"
                  className={style["arrow-icon"]}
                  onClick={() => {
                    navigateTo(
                      `pages/shopitem-detail/index?id=${cartItem.productId}`
                    );
                  }}
                />
              </View>
            </View>
          );
        })}
      </View>

      {/* Summary/Total/Terms */}
      <View className={style["cost-summary"]}>
        {/* Total price */}
        <View className={style["price-container"]}>
          {/* <Paragraph
            onClick={() => {
              navigateTo("pages/terms-conditions/index");
            }}
          >
            请查阅销售条款
          </Paragraph> */}
          <Paragraph color={colors.colorDark} size="small" noSpacing>
            合计
          </Paragraph>
          <PriceView
            className={style["price-view"]}
            price={cartItems.reduce(
              (sum, cartItem) =>
                sum +
                (checkedItems.includes(cartItem.id)
                  ? cartItem.quantity * cartItem.unitPrice
                  : 0),
              0
            )}
            type="heading-n"
            zeroAsNumber
          />
        </View>
      </View>

      {/* I have agreed to conditions + Checkbox */}
      <View className={style["toc-wrapper"]}>
        <C40TermsAndConditions
          checked={agreedToC}
          termsConditionCb={(accepted: boolean) => setAgreedToC(accepted)}
        />
      </View>

      {/* Bottom dock */}
      <View className={style["bottom-dock-wrapper"]}>
        <C13BottomDock
          onPrimaryClick={{
            disabled: !agreedToC || !cartItems.length,
            text: removeCallback ? "提交订单" : "提交申请",
            cb: () => {
              handleSubmit();
            },
          }}
          onSecondaryClick={null}
        />
      </View>
    </UserSubPageBase>
  );
};

export default C33ShoppingCart;
